<template>
  <div>
    <div class="top">
      <div class="fl top-left">考核人员列表</div>
    </div>
    <div class="body">
        <div class="fl" style="line-height:30px">专业：</div>
        <el-select size="mini" clearable filterable v-model="tiaojian.professionId" @change="getData()" style="float:left;width:150px;margin-right:10px">
          <el-option
            v-for="item in type_zhuanye"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <el-input size="mini" v-model="tiaojian.name" @input="getData()" clearable class="fl top-right" suffix-icon="el-icon-search" placeholder="请输入搜索的姓名" />
        <el-upload
          :disabled="pd_timu"
          style="margin-right:10px"
          class="upload-demo fl"
          :action="urlFile"
          :show-file-list="false"
          :headers="header"
          :on-success="sucessTimu"
          :on-progress="progressTimu"
          multiple>
          <el-button :loading="pd_timu" size="mini" type="primary">批量上传考生</el-button>
        </el-upload>
        <el-button type="primary" size="mini" style="margin-bottom:20px" @click="dialogAdd()">新增考生</el-button>
        <el-button style="margin-left:10px" class="fr" type="primary" size="mini" title="" @click="daochu('2')" title="下载批量上传考生模板">批量上传模板</el-button>
        <el-button style="margin-left:10px" class="fr" type="primary" size="mini" title="" @click="daochu('1')" title="下载全部考生数据">导出考生</el-button>
       <el-table
          :header-cell-style="{
            'background-color': '#FAFAFA',
            'height': '54px',
            'color': '#000000',
            'font-size': '14px',
            'font-weight': 'bold'
        }"
          :data="tableData"
          size="mini"
          empty-text="暂无数据"
          stripe
          style="width: 100%">
          <!-- <el-table-column
            label="头像"
            align="center"
            width="180">
             <template slot-scope="scope">
                <el-image :src="scope.row.portrait"></el-image>
            </template>
          </el-table-column> -->
          <el-table-column
            label="姓名"
            align="center"
            width="80">
             <template slot-scope="scope">
                {{scope.row.name}}
            </template>
          </el-table-column>
          <el-table-column
            label="专业">
             <template slot-scope="scope">
                {{qiehuan(scope.row.professionId, type_zhuanye,'value','name')||'-'}}
            </template>
          </el-table-column>
          <el-table-column
            label="单位">
             <template slot-scope="scope">
                <span :title="scope.row.workUnit">{{scope.row.workUnit||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="职级">
             <template slot-scope="scope">
                <span :title="scope.row.level">{{scope.row.level||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="人员类别">
             <template slot-scope="scope">
                <span :title="scope.row.type">{{scope.row.type||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="成绩统计">
             <template slot-scope="scope">
                <el-button type="text" @click="chengji(scope.row)">历史成绩</el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150">
             <template slot-scope="scope">
                <el-button type="text" @click="xiugai(scope.row)">修改</el-button>
                <el-button v-if="scope.row.logicalDelete" type="text" @click="tingyong(scope.row, false)">启用</el-button>
                <el-button v-else type="text" style="color:red" @click="tingyong(scope.row, true)">停用</el-button>
                <!-- <el-button type="text" @click="shanchu(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div style="width:100%;height:30px;margin-top: 24px;">
          <el-pagination
            style="float:right"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :hide-on-single-page="false"
            :current-page="tiaojian.page"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-size="tiaojian.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
    </div>
    <el-dialog title="维护数据" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-row>
          <el-col class="mb" :span="span1">
            <span class="mt must">专业：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-select size="mini" clearable filterable v-model="form.professionId" style="width:100%">
              <el-option
                v-for="item in type_zhuanye"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt must">类别：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-select size="mini" filterable v-model="form.type" @change="form.rank='';form.level=''" style="width:100%">
              <el-option
                v-for="item in type_leibie"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt must">军衔：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-select v-if="form.type=='指挥军官'||form.type=='专业技术军官'" size="mini" filterable v-model="form.rank" style="width:100%">
              <el-option
                v-for="item in type_junxian[0]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
            <el-select v-else size="mini" filterable v-model="form.rank" style="width:100%">
              <el-option
                v-for="item in type_junxian[1]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt">职级：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-select v-if="form.type=='指挥军官'" size="mini" filterable v-model="form.level" style="width:100%">
              <el-option
                v-for="item in type_zhiji[0]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
            <el-select v-else-if="form.type=='专业技术军官'" size="mini" filterable v-model="form.level" style="width:100%">
              <el-option
                v-for="item in type_zhiji[1]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
            <el-select v-else size="mini" filterable v-model="form.level" style="width:100%">
              <el-option
                v-for="item in type_zhiji[2]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt">单位：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.workUnit" />
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt must">姓名：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.name" />
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt">性别：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-select size="mini" clearable filterable v-model="form.sex" style="width:100%">
              <el-option
                v-for="item in type_xingbie"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt must">身份证号：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.idcard	" />
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt">手机号：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.phone" />
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in phones" :key="index">
          <el-col class="mb" :span="span1">
            <span class="mt" :class="index===0?'must':''">固定电话{{index + 1}}：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="phones[index]" placeholder="输入一个固定电话即可" />
          </el-col>
        </el-row>
        <el-row>
          <el-col class="mb" :span="span1">
            <span class="mt must">帐号：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.account" />
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt must">密码：</span>
          </el-col>
          <el-col class="mb" :span="span2">
            <el-input size="mini" v-model="form.password" />
          </el-col>
          <el-col class="mb" :span="span1">
            <span class="mt">头像上传：</span>
          </el-col>
          <el-col class="mb" :span="span2">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="个人成长轨迹图" width="90%" :visible.sync="dialogChengji">
      <div id="main" style="width: 100%;height:60vh;"></div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChengji = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import $http from '@/utils/request'
import $httpJSON from '@/utils/requestJSON'
import $httpFORM from '@/utils/requestFORM'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data () {
    return {
      pd_timu: false,
      urlFile: '',
      url: '',
      phones: ['', '', ''], // 固定电话
      pd_kaosheng: false,
      header: {
        token: ''
      },
      dialogFormVisible: false,
      dialogChengji: false,
      span1: 5,
      span2: 15,
      imageUrl: '',
      type_all: [],
      type_zhuanye: [],
      type_xingbie: [{
        name: '男',
        value: '男',
      }, {
        name: '女',
        value: '女',
      }],
      type_leibie: [{
        name: '指挥军官',
        value: '指挥军官',
      }, {
        name: '专业技术军官',
        value: '专业技术军官',
      }, {
        name: '士官',
        value: '士官',
      }],
      type_zhiji: [[{
        name: '正军职',
        value: '正军职',
      }, {
        name: '副军职',
        value: '副军职',
      }, {
        name: '正师职',
        value: '正师职',
      }, {
        name: '副师职',
        value: '副师职',
      }, {
        name: '正团职',
        value: '正团职',
      }, {
        name: '副团职',
        value: '副团职',
      }, {
        name: '正营职',
        value: '正营职',
      }, {
        name: '副营职',
        value: '副营职',
      }, {
        name: '正连职',
        value: '正连职',
      }, {
        name: '副连职',
        value: '副连职',
      }, {
        name: '正排职',
        value: '正排职',
      }], [{
        name: '专业技术一级',
        value: '专业技术一级',
      }, {
        name: '专业技术二级',
        value: '专业技术二级',
      }, {
        name: '专业技术三级',
        value: '专业技术三级',
      }, {
        name: '专业技术四级',
        value: '专业技术四级',
      }, {
        name: '专业技术五级',
        value: '专业技术五级',
      }, {
        name: '专业技术六级',
        value: '专业技术六级',
      }, {
        name: '专业技术七级',
        value: '专业技术七级',
      }, {
        name: '专业技术八级',
        value: '专业技术八级',
      }, {
        name: '专业技术九级',
        value: '专业技术九级',
      }, {
        name: '专业技术十级',
        value: '专业技术十级',
      }, {
        name: '专业技术十一级',
        value: '专业技术十一级',
      }, {
        name: '专业技术十二级',
        value: '专业技术十二级',
      }, {
        name: '专业技术十三级',
        value: '专业技术十三级',
      }, {
        name: '专业技术十四级',
        value: '专业技术十四级',
      }], [{
        name: '无职级',
        value: '无职级',
      }]],
      type_junxian: [[{
        name: '少将',
        value: '少将',
      }, {
        name: '大校',
        value: '大校',
      }, {
        name: '上校',
        value: '上校',
      }, {
        name: '中校',
        value: '中校',
      }, {
        name: '少校',
        value: '少校',
      }, {
        name: '上尉',
        value: '上尉',
      }, {
        name: '中尉',
        value: '中尉',
      }, {
        name: '少尉',
        value: '少尉',
      }], [{
        name: '一级军士长',
        value: '一级军士长',
      }, {
        name: '二级军士长',
        value: '二级军士长',
      }, {
        name: '三级军士长',
        value: '三级军士长',
      }, {
        name: '四级军士长',
        value: '四级军士长',
      }, {
        name: '上士',
        value: '上士',
      }, {
        name: '中士',
        value: '中士',
      }, {
        name: '下士',
        value: '下士',
      }, {
        name: '上等兵',
        value: '上等兵',
      }, {
        name: '列兵',
        value: '列兵',
      }]],
      tableData: [],
      total: 50,
      tiaojians: [],
      dialog_tiaojians: [],
      tiaojian: {
        page: 1,
        size: 10,
        name: '',
        rankId: '',
        departmentId: '',
        positionId: '',
        professionId: ''
      },
      form: {
        telephone: '', // 多个固定电话逗号拼接的字符串
        workUnit: '', // 单位
        rank: '', // 军衔
        type: '', // 类别
        level: '', // 职级
        name: '',
        account: '',
        password: '',
        portrait: '',
        id: '',
        idcard: '', // 身份证号
        phone: '',
        professionId: '',
        sex: ''
      },
      option: {
        tooltip: {
            trigger: 'axis',
            formatter: '{b}: {c}分'
        },
        xAxis: {
            type: 'category',
            name: '考场名称',
            data: []
        },
        yAxis: {
            type: 'value',
            name: '分数（分）'
        },
        series: [{
            data: [],
            type: 'line'
        }]
      },
      chengjiList: []
    }
  },
  mounted() {
    this.urlFile = localStorage.getItem('basePath') + '/excel/examinee/upload'
    this.url = localStorage.getItem('basePath') + '/file/upload/eimage'
    this.header.token = getToken()
    this.getData()
    // this.getAll()
    this.getZhuanye()
  },
  methods: {
    chengji(val){
      $http.get('/examinee/score/' + val.id).then(response => {
        if (response.success) {
          let listX = []
          let listY = []
          for (let i =0; i < response.data.length; i++) {
            listX.push(response.data[i].name)
            listY.push(response.data[i].total_score)
          }
          this.option.xAxis.data = listX
          this.option.series[0].data = listY
          
          this.dialogChengji = true
          console.log(this.option)
          this.$nextTick(res=>{
            // 基于准备好的dom，初始化echarts实例
            var echarts = require('echarts');
            var myChart = echarts.init(document.getElementById('main'));
            myChart.setOption(this.option)
          })
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    getData() {
      // this.tiaojian.rankId = this.tiaojians.length > 0?this.tiaojians[0]:''
      // this.tiaojian.departmentId = this.tiaojians.length > 1?this.tiaojians[1]:''
      // this.tiaojian.positionId = this.tiaojians.length > 2?this.tiaojians[2]:''
      // this.tiaojian.professionId = this.tiaojians.length > 3?this.tiaojians[3]:''
      $http.get('/examinee/query/list', {params: this.tiaojian}).then(response => {
        if (response.success) {
          this.tableData  = response.data.list
          this.total  = response.data.total
        } else  {
          this.$message.error({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
    },
    getAll() {
      $http.get('/examinee/grade/get/all').then(response => {
        if (response.success) {
          this.type_all = response.data
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    getZhuanye() {
      $http.get('/examinee/profession/getlist').then(response => {
        if (response.success) {
          let table = []
          for(let i = 0; i < response.data.list.length; i++) {
            table.push({
              name: response.data.list[i].name,
              id: response.data.list[i].id,
              value: response.data.list[i].id,
            })
          }
          this.type_zhuanye = table
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    dialogAdd() {
      this.imageUrl = ''
      this.form = {
        telephone: '', // 多个固定电话逗号拼接的字符串
        workUnit: '', // 单位
        rank: '', // 军衔
        type: '', // 类别
        level: '', // 职级
        name: '',
        account: '',
        password: '',
        portrait: '',
        id: '',
        idcard: '', // 身份证号
        phone: '',
        professionId: '',
        sex: ''
      }
      this.dialogFormVisible = true
    },
    xiugai(item) {
      console.log(item)
      for(let i in this.form) {
        this.form[i] = item[i]
      }
      this.phones=['','','']
      if (this.form.telephone || this.form.telephone + '' === '0') {
        this.phones[0] = this.form.telephone.split(',').length>0?this.form.telephone.split(',')[0]:''
        this.phones[1] = this.form.telephone.split(',').length>1?this.form.telephone.split(',')[1]:''
        this.phones[2] = this.form.telephone.split(',').length>2?this.form.telephone.split(',')[2]:''
      }
      this.imageUrl = item.portrait
      this.dialogFormVisible = true
    },
    tingyong (val,pd) {
      // this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.$message({
      //       type: 'success',
      //       message: '操作成功!'
      //     })
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消操作'
      //     }) 
      //   })
      $http.post('/examinee/remove/logical' + '?id=' + val.id + '&logical=' + pd,).then(response => {
        if (response.success) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          val.logicalDelete = pd
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    shanchu (val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          $httpFORM.post('/examinee/remove', this.qs.stringify({
            id: val.id
          })).then(response => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getData()
            } else  {
              this.$message({
                message: response.msg,
                type: 'error',
                duration: 2000
              })
            }
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          }) 
        })
    },
    yanzheng() {
      let str = ''
      for (let i = 0; i < this.phones.length; i++) {
        if(this.phones[i]!==''&&str!=='') {
          str = str + ',' + this.phones[i]
        }
        if(this.phones[i]!==''&&str==='') {
          str += this.phones[i]
        }
      }
      if (this.form.professionId === '') {
        this.$message.success('请选择专业')
        return false
      }
      if (this.form.rank === '') {
        this.$message.success('请选择军衔')
        return false
      }
      if (this.form.type === '') {
        this.$message.success('请选择类别')
        return false
      }
      if (this.form.name === '') {
        this.$message.success('请输入姓名')
        return false
      }
      if (this.form.idcard === '') {
        this.$message.success('请输入身份证号')
        return false
      }
      if (this.form.account === '') {
        this.$message.success('请输入账号')
        return false
      }
      if (this.form.password.length < 6) {
        this.$message.success('请输入最少为6位的密码')
        return false
      }
      if (str === '') {
        this.$message.success('请输入至少一个固定电话')
        return false
      }
      // if (this.imageUrl === '') {
      //   this.$message.success('请上传照片')
      //   return false
      // }
      return true
    },
    submit() {
      if (!this.yanzheng()) {
        return
      }
      this.form.portrait = this.imageUrl
      let str = ''
      for (let i = 0; i < this.phones.length; i++) {
        if(this.phones[i]!==''&&str!=='') {
          str = str + ',' + this.phones[i]
        }
        if(this.phones[i]!==''&&str==='') {
          str += this.phones[i]
        }
      }
      this.form.telephone = str
      console.log(this.form)
      if (this.form.id) {
        $httpJSON.post('/examinee/amend', this.form).then(response => {
          if (response.success) {
            this.dialogFormVisible = false
            this.getData()
          } else  {
            this.$message({
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        }).catch(error => {
          console.log(error)
        })
      } else {
        $httpJSON.post('/examinee/add', this.form).then(response => {
          if (response.success) {
            this.dialogFormVisible = false
            this.getData()
          } else  {
            this.$message({
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.tiaojian.size = val
      this.getData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.tiaojian.page = val
      this.getData()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if (res.success) {
        this.imageUrl = res.data
      } else  {
        this.$message.error('上传失败');
      }
    },
    beforeAvatarUpload(file) {
      // 上传前控制上传文件大小类型
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
      return true;
    },
    progressKaosheng() {
      this.pd_kaosheng = true
    },
    sucessKaosheng(response, file, fileList) {
      this.pd_kaosheng = false
      if (response.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          } else  {
            this.$message({
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
    },
    
    progressTimu() {
      this.pd_timu = true
    },
    sucessTimu(response, file, fileList) {
      this.pd_timu = false
      if (response.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.tiaojian.page = 1
            this.getData();
          } else  {
            this.$message({
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
    },
    daochu(e) {
      if (e==='1') {
        window.location.href = localStorage.getItem('basePath') + '/excel/examinee/download'
      } else {
        window.location.href = localStorage.getItem('basePath') + '/excel/examinee/template/download'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.top{
  width:100%;
  // height: 40px;
  padding-bottom: 20px;
  background-color: white;
}
.top-left{
  line-height:30px;
  font-size: 20px;
  color: #333333;
}
.top-right{
  width: 150px;
  line-height:30px;
  margin-right: 10px;
}
.body{
  margin:24px 0 30px 24px;
  padding: 20px 32px 24px 32px;
  width: calc(100% - 48px);
  // height: calc(100vh - 0px);
  background-color: white;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
